package com.ustcinfo.study.hbase.r1.zhangshouxin;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;

import java.io.IOException;
/**
 * Describe:HBase建表
 * Author: 张守信
 */
public class HbaseCreateTable{
    /*集群配置对象*/
    private static Configuration conf = null;

    /*集群连接对象*/
    private static Connection connection = null;

    /*hbase集群管理对象*/
    private static Admin admin = null;

    /*hbase replication管理对象*/
    private static ReplicationAdmin replicationAdmin = null;

    /**
     * 初始化
     */
    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conf.set("hbase.zookeeper.quorum", "nodex,nodex1,nodex2");
        try {
            connection = ConnectionFactory.createConnection(conf);//根据集群配置创建集群连接
            admin = connection.getAdmin();//创建集群管理对象
            replicationAdmin = new ReplicationAdmin(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static boolean tableExist(String name) {//判断表是否存在
        try {
            return admin.tableExists(TableName.valueOf(name));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 创建表
     * @param name
     * @param families
     */
    public static void createTable(String name, String... families) {
        TableName tableName = TableName.valueOf(name);//获取表名
        HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);//创建表描述
        if (!tableExist(name)) {
            for (String family : families) {
                HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(family);//创建列簇描述
                hTableDescriptor.addFamily(hColumnDescriptor);//添加列簇
            }
            try {
                admin.createTable(hTableDescriptor);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {


        if(tableExist("BD_TEST"))
        {
            System.out.println("表已存在");
        }
        else {
            createTable("BD_TEST", "F1", "F2");

        }
    }

}
